
package CelestialWeb;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;

import CelestialDataAccess.*;
import CelestialWorkflow.EmployeesControl;
import CelestialDataStructures.*;

public class EmployeesServlet extends HttpServlet {

    private WriteXMLError m_WriteError = new WriteXMLError();
    private EmployeesControl m_EmployeesControl = new EmployeesControl();
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String strAction = request.getParameter("action");

        if(strAction.compareTo("search")==0)
            searchEmployees(request, response);

        else if(strAction.compareTo("get")==0)
            getEmployee(request, response);

        else if(strAction.compareTo("update")==0)
            updateEmployee(request, response);

        else if(strAction.compareTo("insert")==0)
            insertEmployee(request, response);

        else if(strAction.compareTo("delete")==0)
            deleteEmployee(request, response);
        
        else if(strAction.compareTo("get_added_today")==0)
            getAddedToday(request, response);
        
        else return;
    }
    /*************************************************************************/
    private void searchEmployees(HttpServletRequest request, HttpServletResponse response) throws IOException{

        String strSearchFor = request.getParameter("search_for");
        String strSearchField = request.getParameter("search_field");
        
        ArrayList<Employee> lstEmployees = new ArrayList<Employee>();

        m_EmployeesControl.searchEmployees(strSearchFor, strSearchField, lstEmployees);

        if(m_EmployeesControl.hasError())
            m_WriteError.doForEach(m_EmployeesControl.getErrors());
        else{
            /* no errors, return employee records in XML */
            response.setContentType("text/xml");
            response.setHeader("cache-control", "no-cache");
            PrintWriter pw = response.getWriter();

            pw.println("<Employees>");
            for(Employee emp: lstEmployees)
                writeEmployeeXML(emp, pw);
            pw.println("</Employees>");
        }

    }
    /*************************************************************************/
    private void getEmployee(HttpServletRequest request, HttpServletResponse response) throws IOException{

        int iEmployeeID = Integer.parseInt(request.getParameter("emp_id"));
        Employee emp = m_EmployeesControl.getEmployee(iEmployeeID);

        if(m_EmployeesControl.hasError())
            m_WriteError.doForEach(m_EmployeesControl.getErrors());
        else{
            /* no errors, write employee XML */
            assert(emp!=null);
            
            response.setContentType("text/xml");
            response.setHeader("cache-control", "no-cache");
            PrintWriter pw = response.getWriter();

            pw.println("<Employees>");
            writeEmployeeXML(emp, pw);
            pw.println("</Employees>");
        }
    }
    /*************************************************************************/
    private void updateEmployee(HttpServletRequest request, HttpServletResponse response){
        
        m_EmployeesControl.updateEmployee(request.getParameterMap());

        if(m_EmployeesControl.hasError())
            m_WriteError.doForEach(m_EmployeesControl.getErrors());
    }
    /*************************************************************************/
    private void insertEmployee(HttpServletRequest request, HttpServletResponse response){

        m_EmployeesControl.insertEmployee(request.getParameterMap());

        if(m_EmployeesControl.hasError())
            m_WriteError.doForEach(m_EmployeesControl.getErrors());
    }
    /*************************************************************************/
    private void deleteEmployee(HttpServletRequest request, HttpServletResponse response) throws IOException{

        response.setHeader("cache-control", "no-cache");
        response.setContentType("text/xml");
        PrintWriter pw = response.getWriter();

        String[] strID = request.getParameter("id").split(":");
        ArrayList<Integer> lstIDs = new ArrayList<Integer>();
        Integer iID;

        for(String id: strID){
            iID = Integer.parseInt(id);
            m_EmployeesControl.deleteEmployee(iID);

            if(m_EmployeesControl.hasError()){
                m_WriteError.setPrintWriter(pw);
                m_WriteError.doForEach(m_EmployeesControl.getErrors());
                return;
            }
            lstIDs.add(iID);
        }
        /* reply which employees are deleted */
        pw.println("<IDs>");
        for(Integer id: lstIDs) pw.println("<ID>" + id + "</ID>");
        pw.println("</IDs>");
    }
    /*************************************************************************/
    private void getAddedToday(HttpServletRequest request, HttpServletResponse response) throws IOException{

        ArrayList<Employee> lstEmployees = new ArrayList<Employee>();
        m_EmployeesControl.getAddedToday(lstEmployees);

        if(m_EmployeesControl.hasError())
            m_WriteError.doForEach(m_EmployeesControl.getErrors());
        else{
            /* no errors, write employee XML */
            response.setContentType("text/xml");
            response.setHeader("cache-control", "no-cache");
            PrintWriter pw = response.getWriter();

            pw.println("<Employees>");
            for(Employee emp: lstEmployees)
                writeEmployeeXML(emp, pw);
            pw.println("</Employees>");
        }
    }
    /*************************************************************************/
    /* Helpers */
    private void writeEmployeeXML(Employee emp, PrintWriter pw){

        pw.println("<Employee>");
        pw.println("<FirstName>" + emp.getFirstName() + "</FirstName>");
        pw.println("<LastName>" + emp.getLastName() + "</LastName>");
        pw.println("<EmployeeID>" + emp.getEmployeeID() + "</EmployeeID>");
        pw.println("<EmployedOn>" + DateFormat.formatLong(emp.getEmploymentDate()) + "</EmployedOn>");
        pw.println("<Password>" + emp.getPassword() + "</Password>");
        pw.println("<DOB>" + DateFormat.formatLong(emp.getDOB()) + "</DOB>");
        pw.println("<Contact>" + emp.getContact() + "</Contact>");
        pw.println("<Email>" + emp.getEmail() + "</Email>");
        pw.println("<AddressLine1>" + emp.getAddressLine1() + "</AddressLine1>");
        pw.println("<AddressLine2>" + emp.getAddressLine2() + "</AddressLine2>");
        pw.println("<PostalCode>" + emp.getPostalCode() + "</PostalCode>");
        pw.println("</Employee>");
    }
    /*************************************************************************/
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
